package com.green.card.fragment;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.green.card.R;
import com.green.card.ReturnCashActivity;
import com.green.card.base.BaseFragment;
import com.green.card.constants.Config;
import com.green.card.utils.NetWorkUtils;
import com.green.card.utils.ShareUtils;
import com.green.card.utils.ToastUtils;
import com.green.card.utils.ZYALogUtils;
import com.leona.splashlibrary.BrowserActivity;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.apache.http.util.EncodingUtils;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by admin on 2018/1/25.
 */

public class HomeFragment extends BaseFragment implements View.OnClickListener{
    private Activity context;

    //webView控件
       WebView webView;
    // 根布局
    private RelativeLayout mLinearLayoutl;
    //没有网络错误图片
    private ImageButton  mIbError;
    // 包号
    private String p;

    private ImageView shareIV, returnCashIV ;

    @Override
    protected int setContentView() {
        int fragmentHome = R.layout.fragment_home;
        return fragmentHome;
    }

    @Override
    public void findView(View view) {
        mLinearLayoutl = (RelativeLayout) view.findViewById(R.id.ll);
        webView = (WebView) view.findViewById(R.id.main_web);
        mIbError = (ImageButton) view.findViewById(R.id.main_ib);
        shareIV = (ImageView) view.findViewById(R.id.share_iv);
        shareIV.setOnClickListener(this);
        returnCashIV = (ImageView) view.findViewById(R.id.return_cash_iv);
        returnCashIV.setOnClickListener(this);

        initWebView();
    }

    @Override
    public void initData(Activity context) {
        p = getRawFileContent(context, R.raw.p);
        //判断是否有网络连接
        boolean isConnect = NetWorkUtils.isNetworkConnected(context);
        if (isConnect){//当有网络
            okHttpToService(context);
        }else {//没开网络时，加载失败并提示用户打开网络
            ToastUtils.toast(context,"当前没有网络连接，点击屏幕现在去打开网络");
            mIbError.setVisibility(View.VISIBLE);
            webView.setVisibility(View.GONE);
            //设置点击事件，点击屏幕跳转设置网络
            mLinearLayoutl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                }
            });
            mIbError.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                }
            });
        }
    }


    /**
     * 使用okHttp请求服务器拿到56卡汇链接
     * @param context
     */
    private void okHttpToService(final Activity context) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    //包号
                    String packId = getRawFileContent(context, R.raw.p);
                    String url = Config.ZYA_URL+"?packId="+packId;
                    ZYALogUtils.d("url-->"+url);
                    Request request = new Request.Builder()
                            .url(url)
                            .build();
                    Response response = client.newCall(request).execute();
                    final String bankUrl = response.body().string();
                    ZYALogUtils.d("bankUrl-->"+bankUrl);
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showWeb(bankUrl);
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /**
     * 展示56卡汇
     * @param bankUrl
     *          银行链接
     */
    private void showWeb(String bankUrl) {
        WebSettings settings = webView.getSettings();
        // 显示放大缩小
        settings.setBuiltInZoomControls(true);
        // 设置可以支持缩放
        settings.setSupportZoom(true);
        //为图片添加放大缩小功能
        settings.setUseWideViewPort(true);
        //支持javascript
        settings.setJavaScriptEnabled(true);
        //不显示webview缩放按钮
        settings.setDisplayZoomControls(false);
        if (bankUrl.isEmpty()){
            //如果返回空链接，那么就加载默认的
            webView.loadUrl("http://work.zhuoyian.com/Api/card?id=05AD35");
        }else {
            webView.loadUrl(bankUrl);
        }
    }


    /**
     * 获取raw目录下的包号
     * @param context
     * @param Id
     * @return
     */
    private static String getRawFileContent(Context context, int Id) {
        String ret = "";
        try {
            InputStream is = context.getResources().openRawResource(Id);
            int len = is.available();
            byte[] buffer = new byte[len];
            is.read(buffer);
            ret = EncodingUtils.getString(buffer, "utf-8");
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.share_iv: {
                ShareUtils.showShare(getActivity(), R.drawable.icon);
//                ShareUtils.showShare(getActivity());
                break;
            }case R.id.return_cash_iv: {
                startActivity(new Intent(getActivity(), ReturnCashActivity.class));
                break;
            }
        }
    }

    private void initWebView() {
        com.tencent.smtt.sdk.WebSettings settings = webView.getSettings();
        settings.setPluginState(com.tencent.smtt.sdk.WebSettings.PluginState.ON);
        if (Build.VERSION.SDK_INT > 16) {//设置视频自动播放
            settings.setMediaPlaybackRequiresUserGesture(false);
        }
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//支持js自动弹框
        settings.setSupportZoom(true); //支持缩放
        settings.setBuiltInZoomControls(true); //支持手势缩放
        settings.setDisplayZoomControls(false); //是否显示缩放按钮
        // >= 19(SDK4.4)启动硬件加速，否则启动软件加速
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            settings.setLoadsImagesAutomatically(true); //支持自动加载图片
        } else {
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            settings.setLoadsImagesAutomatically(false);
        }
        settings.setUseWideViewPort(true); //设置内容自适应屏幕大小
        settings.setLoadWithOverviewMode(true);
        settings.setDatabaseEnabled(true);//设置允许使用数据库
        settings.setAllowFileAccess(true);
        settings.setAppCacheEnabled(true);//允许使用缓存
        settings.setDomStorageEnabled(true);
        settings.setSaveFormData(true);
        settings.setSupportMultipleWindows(true);
        settings.setCacheMode(com.tencent.smtt.sdk.WebSettings.LOAD_DEFAULT); //优先使用缓存
        webView.setHorizontalScrollBarEnabled(false);
        webView.setOverScrollMode(View.OVER_SCROLL_NEVER); // 取消WebView中滚动或拖动到顶部、底部时的阴影
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); // 取消滚动条白边效果
        webView.requestFocus();

        //注意：以下两项是必须设置，其他设置选项根据自身项目需求进行配置
        settings.setJavaScriptEnabled(true); //必须设置
        /*跟H5 JS交互接口*/
//        webView.addJavascriptInterface(null);

        //移除Android系统内部的默认内置接口,存在远程代码执行漏洞
        webView.removeJavascriptInterface("searchBoxJavaBridge_");
        webView.removeJavascriptInterface("accessibility");
        webView.removeJavascriptInterface("accessibilityTraversal");

        //webview中的下载调用系统下载
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String s, String s1, String s2, String s3, long l) {
                Uri uri = Uri.parse(s);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                view.loadUrl(url);
                Intent intent = new Intent(getActivity(), BrowserActivity.class) ;
                intent.putExtra("url", url) ;
                startActivity(intent);
                return true;
            }

            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
                if (shareIV.getVisibility() == View.GONE) {
                    shareIV.setVisibility(View.VISIBLE);
                }
                if (returnCashIV.getVisibility() == View.GONE) {
                    returnCashIV.setVisibility(View.VISIBLE);
                    //添加缩放动画
                    scaleAnimation(returnCashIV);
                }
            }
        });
        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView webView, int i) {
                super.onProgressChanged(webView, i);
            }

            /**
             * Title是用URL的title
             * @param webView
             * @param s
             */
            @Override
            public void onReceivedTitle(WebView webView, String s) {
                super.onReceivedTitle(webView, s);
            }

            /*不设此属性会在有的手机上面打不开广告*/
            @Override
            public boolean onCreateWindow(final WebView webView, boolean b, boolean b1, final Message message) {
                final WebView newWebView = new WebView(webView.getContext());
                newWebView.setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView iview, String url) {
                        webView.loadUrl(url);
                        return true;
                    }
                });
                WebView.WebViewTransport transport = (WebView.WebViewTransport) message.obj;
                transport.setWebView(newWebView);
                message.sendToTarget();
                return true;
            }
        });
    }

    private void scaleAnimation(View view){
       /* AnimationSet aset_3=new AnimationSet(true);
        ScaleAnimation aa_3=new ScaleAnimation(1, 0.1f, 1, 0.1f, Animation.RELATIVE_TO_SELF,1f,Animation.RELATIVE_TO_SELF,1f);
        aa_3.setRepeatMode(ValueAnimator.RESTART);
        aa_3.setRepeatCount(ValueAnimator.INFINITE);
        aa_3.setDuration(1000);
        aset_3.addAnimation(aa_3);
        view.startAnimation(aset_3);*/

        AnimationSet aset=new AnimationSet(true);
        AlphaAnimation aa=new AlphaAnimation(1,0);
        aa.setRepeatMode(ValueAnimator.RESTART);
        aa.setRepeatCount(ValueAnimator.INFINITE);
        aa.setDuration(1000);
        aset.addAnimation(aa);
        view.startAnimation(aset);
    }
}
